package com.wondersgroup.fjzlpt.org.service.impl.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.repository.sql.bean.SQLBean;
import com.quick.framework.boot.repository.sql.bean.table.TableBean;
import com.quick.framework.boot.service.impl.OperationServiceImpl;
import com.quick.framework.exception.ServiceException;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.LoggerUtil;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.FwbgxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.QyxxDAO;
import com.wondersgroup.fjzlpt.org.service.inter.timer.AutoRenewService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 自动续约
 * <p>
 * <p>
 * Created by sanma on 2018/5/21.
 */
@Service
public class AutoRenewServiceImpl extends OperationServiceImpl implements AutoRenewService {

    @Autowired
    private QyxxDAO qyxxDAO;
    @Autowired
    private FwbgxDAO fwbgxDao;

    @Value("${service.drjmxx.count}")
    private String count ;

    @Autowired
    @Qualifier("TB_JTQY_QYXX")
    private TableBean qyxxTableBean;

    @Autowired
    @Qualifier("TB_JTQY_QYSJB")
    private TableBean qysjTableBean;

    @Autowired
    @Qualifier("TB_JTQY_FWBGX")
    private TableBean fwbgxTableBean;

    @Autowired
    @Qualifier("TB_JTQY_YBFWXGX")
    private TableBean ybfwxgxTableBean;

    @Override
    protected void insert(Map map) {
        //查询签约的 服务包ID, 服务包类型, 总费用
        map.putAll(fwbgxDao.queryFwbidsByQyxxid((String)map.get("QYXXID")));
        // 总费用为0 && 未续约
        if(map.get("ZFY").equals("0") && map.get("SFXY").equals("0")){
            /*即将添加的免费续约记录时间与现有正式签约时间段是否重叠(该情况出现在: 医生在页面进行了新增操作)*/
            JSONArray nowQyxxArr = qyxxDAO.queryQyxxByQysj(map);
            boolean addMfxy = true;//添加免费续约(记录)
            for(int i=0;i<nowQyxxArr.size();i++){
                if(nowQyxxArr.getJSONObject(i).getString("ZFY").equals("0")){
                    addMfxy = false;
                    break;
                }
            }
            if(addMfxy){
                update(map);
                String qyxxid = map.get("QYXXID").toString();
                String qyxxid_new = UUID.randomUUID().toString();
                JSONArray ybfwxAry = getYbfwxxx(qyxxid);
                map.put("QYXXID" , qyxxid_new);
                insertQyxx(map);
                insertFwbxx(map);
                if(!ybfwxAry.isEmpty() && ybfwxAry.size() > 0){
                    insertYbfwx(ybfwxAry , qyxxid_new);
                }
                insertQysjxx(map);
            }else{
                map.put("MS","已签约免费服务包, 无法自动续约!");
                update(map);
            }
        }else{
            update(map);
        }
    }

    @Override
    protected void update(Map map) {
        String qylx = "04";
        String ms = "签约已到期！";
        if(!StringUtils.isEmpty((String)map.get("QYZT"))){
            qylx = (String)map.get("QYZT");
        }
        if(!StringUtils.isEmpty((String)map.get("MS"))){
            ms = (String)map.get("MS");
        }
        SQLBean updateQyxx = new SQLBean("update tb_jtqy_qyxx set qylx = ? , SFXY = '1' , ztms = ? where qyxxid = ? ");
        updateQyxx.setParamAry(new Object[]{qylx , ms , map.get("QYXXID")});
        qyxxDAO.execute(updateQyxx);
    }

    @Override
    protected void delete(Map map) {

    }


    @Override
    public JSONArray queryList(Map map) {
        int count = 100 ;
        if(!StringUtils.isEmpty(this.count) && StringUtils.isNumeric(this.count)){
            count = Integer.parseInt(this.count);
        }
        Date nowDate = FormatDate.getDateY_M_D(FormatDate.getDateYYYY_MM_DD(new Date()));
        //step 1 : 查询已到期同时未续约的记录的QYXXID,服务包总费用(c.FY)要为0,即是：免费咯
        StringBuffer sqlWxy = new StringBuffer();
        //QYXXID , JMXXID , YLTDID , YLJGID , QYSJ , SXSJ , JSSJ , USID , QYLX , SFXY , QYFY , SFYX , SFBS
        //事件表需要的字段
        sqlWxy.append("select a.QYXXID,a.JMXXID,a.YLJGID,a.YLJGID PTJGID,b.YLJGMC,a.YLTDID,a.YLTDID TDID,d.TDMC,a.USID,a.USID YSID,c.XM YSXM, \n");
        sqlWxy.append("sysdate QYSJ,a.JSSJ+1 SXSJ,add_months(a.JSSJ,12) JSSJ,a.SFXY,");
        //签约时间段重叠查询需要的字段
        sqlWxy.append("e.ZJLX,e.ZJHM ");
        sqlWxy.append("FROM TB_JTQY_QYXX a LEFT JOIN TB_ZD_YLJGXX b ON a.YLJGID = b.PTJGID \n");
        sqlWxy.append("LEFT JOIN TB_ZD_YLJGRYXX c ON a.USID = c.USERID \n");
        sqlWxy.append("LEFT JOIN TB_TDGL_TDJBXX d ON a.YLTDID = d.TDID \n");
        sqlWxy.append("LEFT JOIN TB_JTQY_JMXX e ON a.JMXXID = e.JMXXID \n");
        sqlWxy.append("where (a.QYLX = '01' or a.QYLX='02') and a.JSSJ < ? ");
        sqlWxy.append("and a.sfyx = '0' and (a.ztms not like '自动续约失败%' or a.ztms is null) and rownum<=?");
        SQLBean beanWxy = new SQLBean(sqlWxy.toString(),nowDate, count);
        return qyxxDAO.queryList(beanWxy);
    }

    /**
     * 插入签约信息
     * @param data
     */
    private void insertQyxx(Map data){
        //QYXXID , JMXXID , YLTDID , YLJGID , QYSJ , SXSJ , JSSJ , USID , QYLX , SFXY , QYFY , SFYX , SFBS
        data.put("SFBS" , "0");
        data.put("SFYX" , "0");
        data.put("SFXY" , "0");
        data.put("QYLX" , "01");
        data.put("QYSJ" , FormatDate.getDate("yyyy-MM-dd HH:mm:ss", data.get("QYSJ").toString()));
        data.put("SXSJ" , FormatDate.getDateY_M_D(data.get("SXSJ").toString()));
        data.put("JSSJ" , FormatDate.getDateY_M_D(data.get("JSSJ").toString()));
        SQLBean insertQyxx = qyxxTableBean.getInsertSQLBean(data);
        qyxxDAO.execute(insertQyxx);
    }


    /**
     * 插入服务包信息
     * @param data
     */
    private void insertFwbxx(Map data){
        //FWBID , FWBSX
        String fwbid = data.get("FWBID").toString();
        String fwbsx = data.get("FWBSX").toString();
        String[] fwbs = fwbid.split(",");
        String[] fwbsxs = fwbsx.split(",");
        List<Map> list = new ArrayList<>();
        for(int i = 0; i < fwbs.length ; i ++ ){
            Map<String , String> item = new HashMap<>();
            item.put("QYXXID" , data.get("QYXXID").toString());
            item.put("FWBID" , fwbs[i]);
            item.put("FWBSX" , fwbsxs[i]);
            list.add(item);
        }
        SQLBean insertFwbxx = fwbgxTableBean.getInsertBatchSQLBean(list);
        qyxxDAO.execute(insertFwbxx);
    }

    /**
     * 插入医保服务项信息
     * @param dataAry
     */
    private void insertYbfwx(JSONArray dataAry , String qyxxid){
        List<Map> list = new ArrayList<>();
        for(int i = 0 ; i < dataAry.size() ; i ++){
            JSONObject item = dataAry.getJSONObject(i);
            item.put("QYXXID" , qyxxid);
            list.add(item);
        }
        SQLBean insertYbwfx = ybfwxgxTableBean.getInsertBatchSQLBean(list);
        qyxxDAO.execute(insertYbwfx);
    }

    /**
     * 插入签约事件信息
     * @param data
     */
    private void insertQysjxx(Map data){
        //ID , PTJGID , YLJGMC , TDID , TDMC , YSID , YSXM
        data.put("ID" , UUID.randomUUID().toString());
        data.put("CZSJ" , new Date());
        data.put("SJLX" , "01");
        data.put("XYID" , "XYID");
        data.put("BZ" , "签约免费包，到期自动续约。");
        SQLBean insertQysj = qysjTableBean.getInsertSQLBean(data);
        qyxxDAO.execute(insertQysj);
    }

    private JSONArray getYbfwxxx(String qyxxid){
        SQLBean queryYbfwx = new SQLBean("select * from TB_JTQY_YBFWXGX where qyxxid = ? ");
        queryYbfwx.setParamAry(new Object[]{qyxxid});
        return qyxxDAO.queryList(queryYbfwx);
    }


    @Override
    public void xyjlToQy() {
        Date nowDate = FormatDate.getDateY_M_D(FormatDate.getDateYYYY_MM_DD(new Date()));
        StringBuffer sqlBufXy = new StringBuffer();
        sqlBufXy.append("update TB_JTQY_QYXX set QYLX = '01' where QYXXID in");
        sqlBufXy.append("(select QYXXID from TB_JTQY_QYXX where 1=1 \n");
        //只能当前没有正常的签约记录再启用续约记录（即：以上一条记录为准，只有上一条记录失效后才能签约）
        sqlBufXy.append("and JMXXID not in(select JMXXID from TB_JTQY_QYXX where qylx='01' )) \n");
        sqlBufXy.append("and sxsj <= ? and QYLX = '05'");
        SQLBean beanXy = new SQLBean(sqlBufXy.toString(), nowDate);
        qyxxDAO.execute(beanXy);
    }
}
